package org.example.coursemangementserver.server.controller;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.example.coursemangementserver.common.exception.common.CommonException;
import org.example.coursemangementserver.common.result.Result ;

import lombok.extern.slf4j.Slf4j;
import org.example.coursemangementserver.common.utils.Aes;
import org.example.coursemangementserver.pojo.dto.UserLoginDTO;
import org.example.coursemangementserver.pojo.dto.UserRegisterDTO;
import org.example.coursemangementserver.pojo.vo.UserLoginVO;
import org.example.coursemangementserver.server.service.interfac.admin.AdminService;
import org.example.coursemangementserver.server.service.interfac.student.StudentService;
import org.example.coursemangementserver.server.service.interfac.teacher.TeacherService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.Random;
import java.util.concurrent.TimeUnit;


/**
 * 与账户操作请求相关的控制器
 * @author 12438
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class loginAndRegisterController {

    /**
     * 注入教务人员相关的业务的逻辑的bean
     */
    @Autowired
    private AdminService adminService;
    /**
     * 注入学生相关的业务的逻辑的bean
     */
    @Autowired
    private StudentService  studentService;
    /**
     * 注入老师相关的业务的逻辑的bean
     */
    @Autowired
    private TeacherService teacherService;

    /**
     * 注入redis对象类
     */
    @Autowired
    private RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();

    /**
     * 账户(学生，老师，教务人员)登录
     */
    @PostMapping("/login")
    public Result<UserLoginVO> userLogin(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("账户登录请求: {}", userLoginDTO);
        if (userLoginDTO.getRole() == 1) {
            //学生登录
            return Result.success(studentService.login(userLoginDTO), "登录成功！！！");
        } else if (userLoginDTO.getRole() == 2) {
            //老师登录
            return Result.success(teacherService.login(userLoginDTO), "登录成功！！！");
        } else {
            //教务人员登录
            return Result.success(adminService.login(userLoginDTO), "登录成功！！！");
        }
    }


    /**
     * 学生，老师提交注册申请
     */
    @PostMapping("/register")
    public Result registerUser(@RequestBody UserRegisterDTO userRegisterDTO) {
        log.info("正在处理前端注册请求：{}", userRegisterDTO);

        //先看验证码的正确性
        String code = userRegisterDTO.getCode();
        String emailAddress = userRegisterDTO.getEmailAddress();
        //获取redis数据库操作对象
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        String rightCode = valueOperations.get("code:"+emailAddress);
        if (rightCode != null) {
            log.info("rightCode:{}",rightCode);
            if (!code.equals(rightCode)) {
                //验证码不匹配
                throw new CommonException("验证码不匹配");
            }
            if (userRegisterDTO.getRole() == 1) {
                //学生注册
                studentService.register(userRegisterDTO);
            } else if (userRegisterDTO.getRole() == 2) {
                //老师注册
                teacherService.register(userRegisterDTO);
            }
            return Result.success();
        }else{//验证码不存在或失效
            throw new CommonException("验证码不存在或者已失效");
        }
    }

    /**
     * 前端用户退出请求
     */
    @GetMapping("/logout")
    public Result userLogout(){
        log.info("正在处理用户退出登录请求");
        return Result.success();
    }

    /**
     * 前端用户发送验证码
     */
    @GetMapping("/sendCode")
    public Result sendCode(String emailAddress){
        log.info("正在处理发送验证码请求:{}",emailAddress);
        //获取redis数据库操作对象
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        String code = getCode();
        log.info("获得随机验证码:{}",code);
        send(emailAddress,code);
        valueOperations.set("code:"+emailAddress,code,5, TimeUnit.MINUTES);
        //将邮箱地址和对应的验证码存入redis数据库,并设置有效时间为5分钟
        log.info("验证码发送成功！");
        return Result.success();
    }
    /**
     * 发送邮件
     * @param receiver
     * @param code
     * @return
     */
    public boolean send(String receiver,String code) {
        // 发送email对象
        HtmlEmail email = new HtmlEmail();
        // 这里是SMTP发送服务器的名字
        email.setHostName("smtp.qq.com");
        //邮箱的SMTP服务器,qq邮箱为smtp.qq.com
        email.setCharset("GBK");
        //设置发送的字符类型
        try {
            email.addTo(receiver);
            //设置收件人
            email.setFrom("1243808154@qq.com","教务人员");
            email.setAuthentication("1243808154@qq.com","abxfrqoifcwpijdg");
            email.setSubject("课程管理系统登录验证码");
            //设置发送主题
            email.setMsg("您的系统登录验证码为："+code+"\n请勿泄露给他人！！");
            //设置发送内容
            email.send();
            //进行发送
            return true;
        } catch (EmailException e) {
            System.out.println("邮箱发送失败");
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 随机生成验证码
     * @return
     */
    public String getCode(){
        //定义验证码的字符集
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        // 创建随机数生成器
        Random random = new Random();
        // 创建一个StringBuilder来存储生成的验证码
        StringBuilder code = new StringBuilder();
        // 生成5位验证码
        for (int i = 0; i < 5; i++) {
            // 从字符集中随机选择一个字符
            int randomIndex = random.nextInt(characters.length());
            char randomChar = characters.charAt(randomIndex);
            // 将选定的字符添加到验证码中
            code.append(randomChar);
        }
        return code.toString();
    }
}

